<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>多视频剪辑工具</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/ffmpeg/0.11.6/ffmpeg.min.js"></script>
    <style>
      * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
        font-family: 'SF Pro Display', 'PingFang SC', 'Helvetica Neue', Arial,
          sans-serif;
      }

      :root {
        --primary-bg: #e6e7ee;
        --secondary-bg: #ffffff;
        --shadow-light: #ffffff;
        --shadow-dark: #d1d9e6;
        --accent-color: #667eea;
        --accent-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --success-color: #4ecdc4;
        --danger-color: #ff6b6b;
        --warning-color: #feca57;
        --text-primary: #2d3748;
        --text-secondary: #718096;
        --glass-bg: rgba(255, 255, 255, 0.25);
        --glass-border: rgba(255, 255, 255, 0.18);
      }

      body {
        background: var(--primary-bg);
        color: var(--text-primary);
        height: 100vh;
        overflow: hidden;
        font-size: 14px;
        transition: all 0.3s ease;
        animation: pageLoad 0.8s ease;
      }

      @keyframes pageLoad {
        from {
          opacity: 0;
          transform: translateY(20px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      .app-container {
        display: flex;
        height: calc(100vh - 40px);
        max-height: 100vh;
        gap: 20px;
        padding: 20px;
        background: var(--primary-bg);
      }

      .left-panel {
        flex: 2;
        background: var(--primary-bg);
        border-radius: 25px;
        box-shadow: 20px 20px 60px var(--shadow-dark),
          -20px -20px 60px var(--shadow-light);
        display: flex;
        flex-direction: column;
        overflow: hidden;
        transition: all 0.3s ease;
      }

      .left-panel:hover {
        box-shadow: 25px 25px 70px var(--shadow-dark),
          -25px -25px 70px var(--shadow-light);
      }

      .right-panel {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 20px;
      }

      .video-list-section {
        flex: 1;
        background: var(--primary-bg);
        border-radius: 25px;
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light);
        overflow-y: auto;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
      }

      .video-list-section::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.1),
          transparent
        );
        transition: left 0.8s;
      }

      .video-list-section:hover::before {
        left: 100%;
      }

      .video-list-section:hover {
        transform: translateY(-2px);
        box-shadow: 16px 16px 32px var(--shadow-dark),
          -16px -16px 32px var(--shadow-light);
      }

      .controls-section {
        height: 300px;
        background: var(--primary-bg);
        border-radius: 25px;
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light);
        display: flex;
        flex-direction: column;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
      }

      .controls-section::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.1),
          transparent
        );
        transition: left 0.8s;
      }

      .controls-section:hover::before {
        left: 100%;
      }

      .controls-section:hover {
        transform: translateY(-2px);
        box-shadow: 16px 16px 32px var(--shadow-dark),
          -16px -16px 32px var(--shadow-light);
      }

      /* 播放器区域 */
      .player-header {
        background: var(--primary-bg);
        padding: 20px 25px;
        border-bottom: none;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: inset 0 -2px 4px rgba(209, 217, 230, 0.3);
      }

      .player-title {
        font-size: 18px;
        font-weight: 600;
        color: var(--accent-color);
        background: var(--accent-gradient);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }

      .player-content {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #000;
        position: relative;
        max-height: 60vh;
        min-height: 300px;
      }

      .main-video {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .no-video-placeholder {
        text-align: center;
        color: var(--text-muted);
        font-size: 18px;
      }

      .player-controls {
        background: var(--primary-bg);
        padding: 20px 25px;
        border-top: none;
        box-shadow: inset 0 2px 4px rgba(209, 217, 230, 0.3);
      }

      .control-bar {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 10px;
      }

      .play-btn {
        background: var(--accent-gradient);
        color: white;
        border: none;
        padding: 12px 20px;
        border-radius: 15px;
        cursor: pointer;
        font-size: 14px;
        min-width: 80px;
        font-weight: 600;
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
      }

      .play-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.2),
          transparent
        );
        transition: left 0.5s;
      }

      .play-btn:hover::before {
        left: 100%;
      }

      .play-btn:hover {
        transform: translateY(-3px);
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2),
          0 0 30px rgba(102, 126, 234, 0.3);
      }

      .play-btn:active {
        transform: translateY(0);
        box-shadow: inset 6px 6px 12px var(--shadow-dark),
          inset -6px -6px 12px var(--shadow-light);
      }

      .time-display {
        font-family: 'Courier New', monospace;
        color: var(--text-secondary);
        min-width: 120px;
        font-size: 13px;
      }

      .progress-container {
        flex: 1;
        height: 16px;
        background: var(--primary-bg);
        border-radius: 20px;
        cursor: pointer;
        position: relative;
        box-shadow: inset 6px 6px 12px var(--shadow-dark),
          inset -6px -6px 12px var(--shadow-light);
        overflow: visible;
      }

      .progress-fill {
        height: 100%;
        background: var(--accent-gradient);
        border-radius: 20px;
        width: 0%;
        transition: width 0.1s ease;
        box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
        position: relative;
        overflow: hidden;
      }

      .progress-fill::after {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.3),
          transparent
        );
        animation: progressShine 2s infinite;
      }

      @keyframes progressShine {
        0% {
          left: -100%;
        }
        100% {
          left: 100%;
        }
      }

      .segment-markers {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        pointer-events: none;
      }

      .segment-marker {
        position: absolute;
        top: -2px;
        width: 2px;
        height: 10px;
        border-radius: 1px;
      }

      .segment-marker.start {
        background: var(--success-color);
      }

      .segment-marker.end {
        background: var(--danger-color);
      }

      .range-selection {
        position: absolute;
        top: 0;
        height: 100%;
        background: rgba(102, 126, 234, 0.3);
        border: 2px solid var(--accent-color);
        border-radius: 4px;
        pointer-events: none;
        z-index: 2;
      }

      .range-selection::before {
        content: '';
        position: absolute;
        left: -2px;
        top: -2px;
        width: 4px;
        height: calc(100% + 4px);
        background: var(--success-color);
        border-radius: 2px;
      }

      .range-selection::after {
        content: '';
        position: absolute;
        right: -2px;
        top: -2px;
        width: 4px;
        height: calc(100% + 4px);
        background: var(--danger-color);
        border-radius: 2px;
      }

      /* 进度条悬停提示 */
      .progress-tooltip {
        position: absolute;
        bottom: 100%;
        left: 0;
        background: rgba(0, 0, 0, 0.9);
        color: white;
        padding: 8px 12px;
        border-radius: 6px;
        font-size: 12px;
        white-space: nowrap;
        pointer-events: none;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.2s ease, visibility 0.2s ease;
        z-index: 1000;
        margin-bottom: 8px;
      }

      .progress-tooltip::after {
        content: '';
        position: absolute;
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
        border: 4px solid transparent;
        border-top-color: rgba(0, 0, 0, 0.9);
      }

      .progress-tooltip.show {
        opacity: 1;
        visibility: visible;
      }

      .progress-preview {
        width: 160px;
        height: 90px;
        background: #000;
        border-radius: 4px;
        margin-bottom: 6px;
        overflow: hidden;
        position: relative;
      }

      .progress-preview video {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .progress-preview-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #666;
        font-size: 24px;
      }

      .mark-buttons {
        display: flex;
        gap: 10px;
      }

      .mark-btn {
        background: var(--primary-bg);
        color: var(--text-primary);
        border: none;
        padding: 10px 16px;
        border-radius: 15px;
        cursor: pointer;
        font-size: 12px;
        font-weight: 600;
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
      }

      .mark-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.2),
          transparent
        );
        transition: left 0.5s;
      }

      .mark-btn:hover::before {
        left: 100%;
      }

      .mark-btn:hover {
        transform: translateY(-3px);
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light);
      }

      .mark-btn:active {
        transform: translateY(0);
        box-shadow: inset 6px 6px 12px var(--shadow-dark),
          inset -6px -6px 12px var(--shadow-light);
      }

      .mark-btn.start {
        color: var(--success-color);
      }

      .mark-btn.end {
        color: var(--danger-color);
      }

      /* 音量控制 */
      .volume-control {
        position: relative;
        display: flex;
        align-items: center;
      }

      .volume-btn {
        background: var(--primary-bg);
        color: var(--text-primary);
        border: none;
        padding: 10px 16px;
        border-radius: 15px;
        cursor: pointer;
        font-size: 16px;
        font-weight: 600;
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        min-width: 50px;
      }

      .volume-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.2),
          transparent
        );
        transition: left 0.5s;
      }

      .volume-btn:hover::before {
        left: 100%;
      }

      .volume-btn:hover {
        transform: translateY(-3px);
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light);
      }

      .volume-btn:active {
        transform: translateY(0);
        box-shadow: inset 6px 6px 12px var(--shadow-dark),
          inset -6px -6px 12px var(--shadow-light);
      }

      .volume-tooltip {
        position: absolute;
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.9);
        color: white;
        padding: 15px 20px;
        border-radius: 12px;
        font-size: 12px;
        white-space: nowrap;
        pointer-events: none;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease;
        z-index: 1000;
        margin-bottom: 10px;
        min-width: 150px;
      }

      .volume-tooltip::after {
        content: '';
        position: absolute;
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
        border: 6px solid transparent;
        border-top-color: rgba(0, 0, 0, 0.9);
      }

      .volume-tooltip.show {
        opacity: 1;
        visibility: visible;
        pointer-events: auto;
        transform: translateX(-50%) translateY(-5px);
      }

      .volume-slider-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
      }

      .volume-slider {
        width: 120px;
        height: 6px;
        border-radius: 3px;
        background: #333;
        outline: none;
        cursor: pointer;
        -webkit-appearance: none;
        appearance: none;
      }

      .volume-slider::-webkit-slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        width: 18px;
        height: 18px;
        border-radius: 50%;
        background: var(--accent-color);
        cursor: pointer;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        transition: all 0.2s ease;
      }

      .volume-slider::-webkit-slider-thumb:hover {
        transform: scale(1.2);
        background: #7c8ef7;
      }

      .volume-slider::-moz-range-thumb {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        background: var(--accent-color);
        cursor: pointer;
        border: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        transition: all 0.2s ease;
      }

      .volume-slider::-moz-range-thumb:hover {
        transform: scale(1.2);
        background: #7c8ef7;
      }

      .volume-slider::-webkit-slider-track {
        height: 6px;
        border-radius: 3px;
        background: linear-gradient(
          to right,
          var(--accent-color) 0%,
          var(--accent-color) var(--volume-percent, 100%),
          #333 var(--volume-percent, 100%),
          #333 100%
        );
      }

      .volume-slider::-moz-range-track {
        height: 6px;
        border-radius: 3px;
        background: #333;
      }

      .volume-percentage {
        font-size: 11px;
        font-weight: 600;
        color: #fff;
        min-width: 35px;
        text-align: center;
      }

      /* 视频列表区域 */
      .section-header {
        background: var(--primary-bg);
        padding: 20px 25px;
        border-bottom: none;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: inset 0 -2px 4px rgba(209, 217, 230, 0.3);
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: var(--accent-color);
        background: var(--accent-gradient);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }

      .upload-btn {
        background: var(--accent-gradient);
        color: white;
        border: none;
        padding: 10px 16px;
        border-radius: 15px;
        cursor: pointer;
        font-size: 12px;
        font-weight: 600;
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
      }

      .upload-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.2),
          transparent
        );
        transition: left 0.5s;
      }

      .upload-btn:hover::before {
        left: 100%;
      }

      .upload-btn:hover {
        transform: translateY(-3px);
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2),
          0 0 30px rgba(102, 126, 234, 0.3);
      }

      .video-list {
        flex: 1;
        overflow-y: auto;
        padding: 20px;
      }

      .video-item {
        background: var(--primary-bg);
        border: none;
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light);
        position: relative;
        overflow: hidden;
      }

      .video-item::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.1),
          transparent
        );
        transition: left 0.8s;
      }

      .video-item:hover::before {
        left: 100%;
      }

      .video-item:hover {
        transform: translateY(-3px);
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light);
      }

      .video-item.active {
        box-shadow: inset 8px 8px 16px var(--shadow-dark),
          inset -8px -8px 16px var(--shadow-light);
        background: rgba(102, 126, 234, 0.1);
      }

      .video-info {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .video-thumbnail {
        width: 60px;
        height: 40px;
        background: #000;
        border-radius: 10px;
        object-fit: cover;
        box-shadow: 4px 4px 8px var(--shadow-dark),
          -4px -4px 8px var(--shadow-light);
      }

      .video-details {
        flex: 1;
        min-width: 0;
      }

      .video-name {
        font-size: 13px;
        font-weight: 500;
        color: var(--text-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-bottom: 4px;
      }

      .video-meta {
        font-size: 11px;
        color: var(--text-muted);
      }

      .segments-list {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 2px solid rgba(102, 126, 234, 0.2);
      }

      .segment-item {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 10px;
        padding: 12px;
        background: var(--primary-bg);
        border-radius: 15px;
        font-size: 11px;
        box-shadow: inset 4px 4px 8px var(--shadow-dark),
          inset -4px -4px 8px var(--shadow-light);
      }

      .segment-time {
        flex: 1;
        display: flex;
        gap: 5px;
      }

      .time-input {
        background: var(--primary-bg);
        border: none;
        color: var(--text-primary);
        padding: 6px 10px;
        border-radius: 10px;
        font-size: 11px;
        width: 100px;
        font-family: 'Courier New', monospace;
        box-shadow: inset 4px 4px 8px var(--shadow-dark),
          inset -4px -4px 8px var(--shadow-light);
        transition: all 0.3s ease;
      }

      .time-input:focus {
        outline: none;
        box-shadow: inset 6px 6px 12px var(--shadow-dark),
          inset -6px -6px 12px var(--shadow-light),
          0 0 0 3px rgba(102, 126, 234, 0.2);
      }

      .remove-segment {
        background: linear-gradient(
          135deg,
          var(--danger-color) 0%,
          #e74c3c 100%
        );
        color: white;
        border: none;
        padding: 6px 10px;
        border-radius: 10px;
        cursor: pointer;
        font-size: 10px;
        font-weight: 600;
        box-shadow: 4px 4px 8px var(--shadow-dark),
          -4px -4px 8px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2);
        transition: all 0.3s ease;
      }

      .remove-segment:hover {
        transform: translateY(-2px);
        box-shadow: 6px 6px 12px var(--shadow-dark),
          -6px -6px 12px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2);
      }

      /* 控制区域 */
      .controls-content {
        flex: 1;
        padding: 25px;
        overflow-y: auto;
      }

      .control-group {
        margin-bottom: 25px;
        padding: 20px;
        background: var(--bg-color);
        border-radius: 15px;
        box-shadow: 6px 6px 12px var(--shadow-dark),
          -6px -6px 12px var(--shadow-light);
        transition: all 0.3s ease;
      }

      .control-group:hover {
        transform: translateY(-2px);
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light);
      }

      .control-group h3 {
        font-size: 15px;
        font-weight: 700;
        background: var(--accent-gradient);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        margin-bottom: 15px;
        text-align: center;
        padding: 8px 0;
      }

      .button-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
        margin-bottom: 15px;
      }

      .action-btn {
        background: var(--primary-bg);
        color: var(--text-primary);
        border: none;
        padding: 14px 20px;
        border-radius: 15px;
        cursor: pointer;
        font-size: 13px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light);
        position: relative;
        overflow: hidden;
      }

      .action-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.2),
          transparent
        );
        transition: left 0.5s;
      }

      .action-btn:hover::before {
        left: 100%;
      }

      .action-btn:hover {
        transform: translateY(-3px);
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light);
      }

      .action-btn:active {
        transform: translateY(0);
        box-shadow: inset 6px 6px 12px var(--shadow-dark),
          inset -6px -6px 12px var(--shadow-light);
      }

      .action-btn:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
        box-shadow: 4px 4px 8px var(--shadow-dark),
          -4px -4px 8px var(--shadow-light);
      }

      .action-btn.primary {
        background: var(--accent-gradient);
        color: white;
        box-shadow: 8px 8px 16px var(--shadow-dark),
          -8px -8px 16px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2);
      }

      .action-btn.primary:hover {
        box-shadow: 12px 12px 24px var(--shadow-dark),
          -12px -12px 24px var(--shadow-light),
          inset 0 1px 0 rgba(255, 255, 255, 0.2),
          0 0 30px rgba(102, 126, 234, 0.3);
      }

      .action-btn.primary:hover {
        background: #3a7bc8;
      }

      .action-btn.success {
        background: var(--success-color);
        border-color: var(--success-color);
        color: white;
      }

      .action-btn.success:hover {
        background: #44a08d;
      }

      .action-btn.danger {
        background: var(--danger-color);
        border-color: var(--danger-color);
        color: white;
      }

      .action-btn.danger:hover {
        background: #e55353;
      }

      .progress-section {
        margin-top: 20px;
        padding: 20px;
        background: var(--bg-color);
        border-radius: 15px;
        box-shadow: inset 6px 6px 12px var(--shadow-dark),
          inset -6px -6px 12px var(--shadow-light);
        transition: all 0.3s ease;
      }

      .progress-bar {
        height: 12px;
        background: var(--bg-color);
        border-radius: 20px;
        overflow: hidden;
        margin-bottom: 12px;
        box-shadow: inset 4px 4px 8px var(--shadow-dark),
          inset -4px -4px 8px var(--shadow-light);
        position: relative;
      }

      .progress-bar .progress-fill {
        height: 100%;
        background: var(--accent-gradient);
        width: 0%;
        transition: width 0.3s ease;
        border-radius: 20px;
        box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);
      }

      .progress-text {
        font-size: 13px;
        color: var(--text-color);
        text-align: center;
        font-weight: 500;
        margin-bottom: 8px;
      }

      .status-message {
        font-size: 13px;
        color: var(--text-secondary);
        margin-top: 12px;
        min-height: 18px;
        padding: 8px 12px;
        border-radius: 8px;
        background: var(--bg-color);
        box-shadow: 2px 2px 4px var(--shadow-dark),
          -2px -2px 4px var(--shadow-light);
        transition: all 0.3s ease;
      }

      .status-message.success {
        color: var(--success-color);
        background: linear-gradient(
          135deg,
          rgba(76, 175, 80, 0.1),
          rgba(139, 195, 74, 0.1)
        );
        box-shadow: 2px 2px 4px var(--shadow-dark),
          -2px -2px 4px var(--shadow-light),
          inset 0 1px 0 rgba(76, 175, 80, 0.2);
      }

      .status-message.error {
        color: var(--danger-color);
        background: linear-gradient(
          135deg,
          rgba(244, 67, 54, 0.1),
          rgba(233, 30, 99, 0.1)
        );
        box-shadow: 2px 2px 4px var(--shadow-dark),
          -2px -2px 4px var(--shadow-light),
          inset 0 1px 0 rgba(244, 67, 54, 0.2);
      }

      /* 隐藏的文件输入 */
      .hidden-input {
        position: absolute;
        left: -9999px;
        opacity: 0;
      }

      /* 响应式设计 */
      @media (max-width: 1024px) {
        .app-container {
          flex-direction: column;
          height: calc(100vh - 20px);
          max-height: none;
          padding: 10px;
          gap: 10px;
        }

        .left-panel {
          height: 50vh;
          min-height: 300px;
          border-radius: 15px;
          box-shadow: 10px 10px 30px var(--shadow-dark),
            -10px -10px 30px var(--shadow-light);
        }

        .player-content {
          max-height: 40vh;
          min-height: 250px;
        }

        .right-panel {
          height: auto;
          flex-direction: row;
          min-height: 200px;
          gap: 10px;
        }

        .controls-section {
          height: auto;
          min-height: 180px;
          border-radius: 15px;
        }

        .video-list-section {
          border-radius: 15px;
        }
      }

      /* 平板横屏优化 */
      @media (max-width: 1024px) and (orientation: landscape) {
        .app-container {
          flex-direction: row;
          height: calc(100vh - 20px);
          padding: 10px;
        }

        .left-panel {
          flex: 2;
          height: auto;
          min-height: auto;
        }

        .right-panel {
          flex: 1;
          flex-direction: column;
          height: auto;
        }

        .player-content {
          max-height: 70vh;
          min-height: 300px;
        }
      }

      /* 手机端优化 */
      @media (max-width: 768px) {
        body {
          font-size: 12px;
        }

        .app-container {
          padding: 8px;
          gap: 8px;
          height: calc(100vh - 16px);
        }

        .left-panel,
        .video-list-section,
        .controls-section {
          border-radius: 12px;
          box-shadow: 8px 8px 20px var(--shadow-dark),
            -8px -8px 20px var(--shadow-light);
        }

        .player-header,
        .section-header {
          padding: 15px 20px;
        }

        .player-title,
        .section-title {
          font-size: 14px;
        }

        .play-btn {
          padding: 10px 16px;
          font-size: 12px;
          min-width: 70px;
        }

        .mark-btn {
          padding: 8px 12px;
          font-size: 11px;
        }

        .upload-btn {
          padding: 8px 12px;
          font-size: 11px;
        }

        .action-btn {
          padding: 12px 16px;
          font-size: 12px;
        }

        .time-display {
          font-size: 11px;
          min-width: 100px;
        }

        .progress-container {
          height: 20px;
        }

        .control-bar {
          gap: 10px;
        }

        .mark-buttons {
          gap: 8px;
        }

        .volume-btn {
          padding: 8px 12px;
          font-size: 14px;
          min-width: 45px;
        }

        .volume-tooltip {
          min-width: 130px;
          padding: 12px 16px;
        }

        .volume-slider {
          width: 100px;
        }

        .video-item {
          padding: 15px;
          margin-bottom: 10px;
          border-radius: 15px;
        }

        .video-thumbnail {
          width: 50px;
          height: 35px;
        }

        .video-name {
          font-size: 12px;
        }

        .video-meta {
          font-size: 10px;
        }

        .controls-content {
          padding: 20px;
        }

        .control-group {
          padding: 15px;
          margin-bottom: 20px;
        }

        .control-group h3 {
          font-size: 13px;
        }
      }

      /* 手机横屏优化 */
      @media (max-width: 768px) and (orientation: landscape) {
        .app-container {
          flex-direction: row;
          height: calc(100vh - 16px);
        }

        .left-panel {
          flex: 2.5;
          height: auto;
        }

        .right-panel {
          flex: 1;
          flex-direction: column;
          min-height: auto;
        }

        .player-content {
          max-height: 80vh;
          min-height: 200px;
        }

        .controls-section {
          height: auto;
          min-height: 150px;
        }

        .video-list-section {
          flex: 1;
        }

        .control-bar {
          flex-wrap: wrap;
          gap: 8px;
        }

        .mark-buttons {
          order: 3;
          width: 100%;
          justify-content: center;
          margin-top: 8px;
        }
      }

      /* 小屏手机优化 */
      @media (max-width: 480px) {
        body {
          font-size: 11px;
        }

        .app-container {
          padding: 5px;
          gap: 5px;
          height: calc(100vh - 10px);
        }

        .left-panel {
          min-height: 280px;
        }

        .player-content {
          min-height: 200px;
        }

        .player-header,
        .section-header {
          padding: 12px 15px;
        }

        .player-title,
        .section-title {
          font-size: 13px;
        }

        .play-btn {
          padding: 8px 12px;
          font-size: 11px;
          min-width: 60px;
        }

        .mark-btn {
          padding: 6px 10px;
          font-size: 10px;
        }

        .upload-btn {
          padding: 6px 10px;
          font-size: 10px;
        }

        .action-btn {
          padding: 10px 12px;
          font-size: 11px;
        }

        .time-display {
          font-size: 10px;
          min-width: 90px;
        }

        .progress-container {
          height: 24px;
        }

        .control-bar {
          gap: 8px;
          margin-bottom: 8px;
        }

        .mark-buttons {
          gap: 6px;
        }

        .volume-btn {
          padding: 6px 10px;
          font-size: 12px;
          min-width: 40px;
        }

        .volume-tooltip {
          min-width: 120px;
          padding: 10px 14px;
        }

        .volume-slider {
          width: 90px;
        }

        .video-item {
          padding: 12px;
          margin-bottom: 8px;
        }

        .video-thumbnail {
          width: 45px;
          height: 30px;
        }

        .controls-content {
          padding: 15px;
        }

        .control-group {
          padding: 12px;
          margin-bottom: 15px;
        }

        .button-grid {
          gap: 8px;
        }
      }

      /* 触摸设备优化 */
      @media (hover: none) and (pointer: coarse) {
        .play-btn,
        .mark-btn,
        .upload-btn,
        .action-btn,
        .volume-btn {
          min-height: 44px;
          touch-action: manipulation;
        }

        .progress-container {
          min-height: 44px;
          padding: 12px 0;
        }

        .video-item {
          min-height: 60px;
          touch-action: manipulation;
        }

        .time-input {
          min-height: 36px;
        }

        .remove-segment {
          min-height: 36px;
          min-width: 36px;
        }
      }
    </style>
  </head>
  <body>
    <div class="app-container">
      <!-- 左侧播放器面板 -->
      <div class="left-panel">
        <div class="player-header">
          <div class="player-title">🎬 视频播放器</div>
        </div>

        <div class="player-content" id="playerContent">
          <div class="no-video-placeholder" id="noVideoPlaceholder">
            <div>📹</div>
            <div>选择视频开始编辑</div>
          </div>
          <video
            class="main-video"
            id="mainVideo"
            style="display: none"
          ></video>
        </div>

        <div class="player-controls">
          <div class="control-bar">
            <button class="play-btn" id="playBtn" disabled>▶️ 播放</button>
            <div class="time-display" id="timeDisplay">00:00 / 00:00</div>
            <div class="progress-container" id="progressContainer">
              <div class="progress-fill" id="mainProgressFill"></div>
              <div class="segment-markers" id="segmentMarkers"></div>
              <div
                class="range-selection"
                id="rangeSelection"
                style="display: none"
              ></div>
              <div class="progress-tooltip" id="progressTooltip">
                <div class="progress-preview" id="progressPreview">
                  <div class="progress-preview-placeholder">📹</div>
                </div>
                <div class="progress-time" id="progressTime">00:00</div>
              </div>
            </div>
            <div class="mark-buttons">
              <button class="mark-btn start" id="markStartBtn" disabled>
                📍 标记起始
              </button>
              <button class="mark-btn end" id="markEndBtn" disabled>
                🏁 标记结束
              </button>
            </div>
            <div class="volume-control">
              <button class="volume-btn" id="volumeBtn">
                🔊
              </button>
              <div class="volume-tooltip" id="volumeTooltip">
                <div class="volume-slider-container">
                  <input type="range" class="volume-slider" id="volumeSlider" min="0" max="100" value="100">
                  <div class="volume-percentage" id="volumePercentage">100%</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 进度展示区域 -->
        <div class="progress-section">
          <div class="progress-bar">
            <div class="progress-fill" id="progressFill"></div>
          </div>
          <div class="progress-text" id="progressText">等待开始...</div>
          <div class="status-message" id="statusMessage"></div>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 视频列表区域 -->
        <div class="video-list-section">
          <div class="section-header">
            <div class="section-title">📁 视频列表</div>
            <button class="upload-btn" id="uploadBtn">+ 上传视频</button>
          </div>

          <div class="video-list" id="videoList">
            <!-- 视频列表项将在这里动态生成 -->
          </div>
        </div>

        <!-- 控制区域 -->
        <div class="controls-section">
          <div class="section-header">
            <div class="section-title">🛠️ 操作控制</div>
          </div>

          <div class="controls-content">
            <div class="control-group">
              <h3>批量操作</h3>
              <div class="button-grid">
                <button
                  class="action-btn success"
                  id="mergeSegmentsBtn"
                  disabled
                >
                  🔗 合并片段
                </button>
                <button class="action-btn" id="downloadLogBtn">
                  📋 下载日志
                </button>
              </div>
              <button
                class="action-btn danger"
                id="resetBtn"
                style="width: 100%; margin-top: 10px"
              >
                🔄 重置所有
              </button>
            </div>
            <div class="control-group">
              <h3>片段操作</h3>
              <div class="button-grid">
                <button class="action-btn primary" id="addSegmentBtn" disabled>
                  ➕ 添加片段
                </button>
                <button
                  class="action-btn success"
                  id="processSegmentsBtn"
                  disabled
                >
                  ✂️ 处理片段
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      type="file"
      id="videoInput"
      class="hidden-input"
      accept="video/*"
      multiple
    />

    <script>
      // 全局变量
      const { createFFmpeg, fetchFile } = FFmpeg
      let ffmpeg = null
      let videoFiles = [] // 存储所有视频文件
      let videoSegments = {} // 存储每个视频的片段信息
      let processingLogs = [] // 存储处理日志
      let processedSegments = [] // 存储处理完成的片段
      let currentVideoId = null // 当前选中的视频ID
      
      // 进度条交互相关变量
      let clickTimer = null // 点击定时器
let isLongPress = false // 是否为长按
let isProgressInteracting = false // 标记是否正在进行进度条交互
let longPressThreshold = 300 // 长按阈值（毫秒）

      // DOM 元素
      const videoInput = document.getElementById('videoInput')
      const uploadBtn = document.getElementById('uploadBtn')
      const videoList = document.getElementById('videoList')
      const mainVideo = document.getElementById('mainVideo')
      const noVideoPlaceholder = document.getElementById('noVideoPlaceholder')
      const playBtn = document.getElementById('playBtn')
      const timeDisplay = document.getElementById('timeDisplay')
      const progressContainer = document.getElementById('progressContainer')
      const mainProgressFill = document.getElementById('mainProgressFill')
      const segmentMarkers = document.getElementById('segmentMarkers')
      const markStartBtn = document.getElementById('markStartBtn')
      const markEndBtn = document.getElementById('markEndBtn')
      const addSegmentBtn = document.getElementById('addSegmentBtn')
      const processSegmentsBtn = document.getElementById('processSegmentsBtn')
      const mergeSegmentsBtn = document.getElementById('mergeSegmentsBtn')
      const downloadLogBtn = document.getElementById('downloadLogBtn')
      const resetBtn = document.getElementById('resetBtn')
      const progressFill = document.getElementById('progressFill')
      const progressText = document.getElementById('progressText')
      const statusMessage = document.getElementById('statusMessage')
      const volumeBtn = document.getElementById('volumeBtn')
      const volumeTooltip = document.getElementById('volumeTooltip')
      const volumeSlider = document.getElementById('volumeSlider')
      const volumePercentage = document.getElementById('volumePercentage')

      // 初始化
      async function init() {
        try {
          statusMessage.textContent = '🔄 正在初始化FFmpeg...'
          statusMessage.className = 'status-message'

          // 检查FFmpeg是否可用
          if (typeof createFFmpeg === 'undefined') {
            throw new Error('FFmpeg库未加载')
          }

          ffmpeg = createFFmpeg({
            log: true,
          })

          // 设置日志收集
          ffmpeg.setLogger(({ type, message }) => {
            const timestamp = new Date().toLocaleTimeString()
            const logEntry = `[${timestamp}] [${type}] ${message}`
            processingLogs.push(logEntry)
            console.log(logEntry)
          })

          // 设置进度回调
          ffmpeg.setProgress(({ ratio }) => {
            const percent = Math.round(ratio * 100)
            updateProgress(percent, `处理中... ${percent}%`)
          })

          await ffmpeg.load()
          statusMessage.textContent = '✅ FFmpeg初始化完成'
          statusMessage.className = 'status-message success'

          setTimeout(() => {
            statusMessage.textContent = ''
          }, 3000)
        } catch (error) {
          console.error('FFmpeg初始化失败:', error)
          statusMessage.textContent = `❌ 初始化失败: ${error.message}`
          statusMessage.className = 'status-message error'
        }

        setupEventListeners()
      }

      // 设置事件监听器
      function setupEventListeners() {
        // 上传按钮
        uploadBtn.addEventListener('click', () => {
          videoInput.click()
        })

        // 文件选择
        videoInput.addEventListener('change', handleVideoUpload)

        // 播放控制
        playBtn.addEventListener('click', togglePlayPause)
        mainVideo.addEventListener('timeupdate', updateVideoTime)
        mainVideo.addEventListener('loadedmetadata', updateVideoTime)
        mainVideo.addEventListener('play', () => updatePlayButton(true))
        mainVideo.addEventListener('pause', () => updatePlayButton(false))

        // 进度条悬停
        progressContainer.addEventListener('mouseenter', showProgressTooltip)
        progressContainer.addEventListener('mousemove', updateProgressTooltip)
        progressContainer.addEventListener('mouseleave', hideProgressTooltip)

        // 进度条交互（点击跳转和长按选择）
        progressContainer.addEventListener('mousedown', handleProgressMouseDown)
        progressContainer.addEventListener('mousemove', handleProgressMouseMove)
        progressContainer.addEventListener('mouseup', handleProgressMouseUp)
        document.addEventListener('mouseup', handleProgressMouseUp) // 全局监听，防止鼠标移出进度条

        // 标记按钮
        markStartBtn.addEventListener('click', markStartTime)
        markEndBtn.addEventListener('click', markEndTime)

        // 音量控制
        volumeBtn.addEventListener('click', toggleVolumeTooltip)
        volumeSlider.addEventListener('input', updateVolume)
        
        // 点击其他地方关闭音量tooltip
        document.addEventListener('click', (e) => {
          if (!e.target.closest('.volume-control')) {
            hideVolumeTooltip()
          }
        })

        // 操作按钮
        addSegmentBtn.addEventListener('click', () =>
          addSegment(currentVideoId)
        )
        processSegmentsBtn.addEventListener('click', () => {
          // 显示选择对话框
          const choice = confirm(
            '选择操作方式：\n\n点击"确定" - 直接合并所有片段\n点击"取消" - 分别下载每个片段'
          )
          processAllSegments(choice)
        })
        mergeSegmentsBtn.addEventListener('click', mergeAllSegments)
        downloadLogBtn.addEventListener('click', downloadLogs)
        resetBtn.addEventListener('click', resetAll)
      }

      // 处理视频上传
      function handleVideoUpload(event) {
        const files = Array.from(event.target.files)
        let isFirstVideo = videoFiles.length === 0

        files.forEach((file) => {
          if (file.type.startsWith('video/')) {
            const videoId = Date.now() + Math.random()
            const videoFile = {
              id: videoId,
              file: file,
              name: file.name,
              size: file.size,
              duration: 0,
            }

            videoFiles.push(videoFile)
            videoSegments[videoId] = []

            displayVideoItem(videoFile)

            // 如果是第一个视频，自动选择并播放
            if (isFirstVideo && videoFiles.length === 1) {
              selectVideo(videoId)
            }
          }
        })

        // 清空输入
        videoInput.value = ''

        updateButtonStates()
      }

      // 显示视频项
      function displayVideoItem(videoFile) {
        const videoItem = document.createElement('div')
        videoItem.className = 'video-item'
        videoItem.dataset.videoId = videoFile.id

        // 创建视频预览
        const video = document.createElement('video')
        video.src = URL.createObjectURL(videoFile.file)
        video.className = 'video-thumbnail'
        video.muted = true

        video.addEventListener('loadedmetadata', () => {
          videoFile.duration = video.duration
          updateVideoMeta(videoItem, videoFile)
        })

        const videoInfo = document.createElement('div')
        videoInfo.className = 'video-info'

        const videoDetails = document.createElement('div')
        videoDetails.className = 'video-details'

        const videoName = document.createElement('div')
        videoName.className = 'video-name'
        videoName.textContent = videoFile.name

        const videoMeta = document.createElement('div')
        videoMeta.className = 'video-meta'
        videoMeta.textContent = `大小: ${formatFileSize(videoFile.size)}`

        videoDetails.appendChild(videoName)
        videoDetails.appendChild(videoMeta)

        videoInfo.appendChild(video)
        videoInfo.appendChild(videoDetails)

        const segmentsList = document.createElement('div')
        segmentsList.className = 'segments-list'
        segmentsList.style.display = 'none'

        videoItem.appendChild(videoInfo)
        videoItem.appendChild(segmentsList)

        // 点击选择视频或切换播放/暂停
        videoItem.addEventListener('click', () => {
          // 如果点击的是当前已选中的视频，则切换播放/暂停
          if (currentVideoId === videoFile.id) {
            togglePlayPause()
          } else {
            // 否则选择该视频
            selectVideo(videoFile.id)
          }
        })

        videoList.appendChild(videoItem)
      }

      // 更新视频元信息
      function updateVideoMeta(videoItem, videoFile) {
        const videoMeta = videoItem.querySelector('.video-meta')
        videoMeta.textContent = `大小: ${formatFileSize(
          videoFile.size
        )} | 时长: ${formatTime(videoFile.duration)}`
      }

      // 选择视频
      function selectVideo(videoId) {
        // 移除之前的选中状态
        document.querySelectorAll('.video-item').forEach((item) => {
          item.classList.remove('active')
          item.querySelector('.segments-list').style.display = 'none'
        })

        // 设置当前选中
        const videoItem = document.querySelector(`[data-video-id="${videoId}"]`)
        videoItem.classList.add('active')
        videoItem.querySelector('.segments-list').style.display = 'block'

        currentVideoId = videoId

        // 加载视频到主播放器
        const videoFile = videoFiles.find((v) => v.id === videoId)
        if (videoFile) {
          loadVideoToPlayer(videoFile)
        }

        updateButtonStates()
        updateSegmentDisplay(videoId)
      }

      // 加载视频到播放器
      function loadVideoToPlayer(videoFile) {
        mainVideo.src = URL.createObjectURL(videoFile.file)
        mainVideo.style.display = 'block'
        noVideoPlaceholder.style.display = 'none'

        playBtn.disabled = false
        markStartBtn.disabled = false
        markEndBtn.disabled = false

        mainVideo.addEventListener('loadedmetadata', () => {
          updateVideoTime()
          updateSegmentMarkers()
        })
      }

      // 播放/暂停切换
      function togglePlayPause() {
        if (mainVideo.paused) {
          mainVideo.play()
        } else {
          mainVideo.pause()
        }
      }

      // 更新播放按钮
      function updatePlayButton(isPlaying) {
        playBtn.textContent = isPlaying ? '⏸️ 暂停' : '▶️ 播放'
      }

      // 更新视频时间显示
      function updateVideoTime() {
        if (mainVideo.duration) {
          const current = formatTime(mainVideo.currentTime || 0)
          const duration = formatTime(mainVideo.duration || 0)
          timeDisplay.textContent = `${current} / ${duration}`

          // 更新进度条
          const percent = (mainVideo.currentTime / mainVideo.duration) * 100
          mainProgressFill.style.width = `${percent}%`
        }
      }

      // 进度条跳转
      function seekVideo(event) {
        if (!mainVideo.duration) return

        const rect = progressContainer.getBoundingClientRect()
        const clickX = event.clientX - rect.left
        const percent = clickX / rect.width

        mainVideo.currentTime = percent * mainVideo.duration
      }

      // 标记起始时间
      function markStartTime() {
        if (!currentVideoId || !mainVideo.duration) return

        const currentTime = formatTime(mainVideo.currentTime)

        // 查找或创建片段
        let segments = videoSegments[currentVideoId]
        let targetSegment = segments[segments.length - 1]

        if (!targetSegment || targetSegment.endTime) {
          // 创建新片段
          addSegment(currentVideoId)
          segments = videoSegments[currentVideoId]
          targetSegment = segments[segments.length - 1]
        }

        targetSegment.startTime = currentTime
        updateSegmentDisplay(currentVideoId)
        updateSegmentMarkers()
        updateButtonStates()

        showMessage(`✅ 已标记起始时间: ${currentTime}`, 'success')
      }

      // 标记结束时间
      function markEndTime() {
        if (!currentVideoId || !mainVideo.duration) return

        const currentTime = formatTime(mainVideo.currentTime)
        const segments = videoSegments[currentVideoId]
        const targetSegment = segments[segments.length - 1]

        if (!targetSegment || !targetSegment.startTime) {
          showMessage('❌ 请先标记起始时间', 'error')
          return
        }

        targetSegment.endTime = currentTime
        updateSegmentDisplay(currentVideoId)
        updateSegmentMarkers()
        updateButtonStates()

        showMessage(`✅ 已标记结束时间: ${currentTime}`, 'success')
      }

      // 添加片段
      function addSegment(videoId) {
        if (!videoId) return

        const segmentId = Date.now() + Math.random()
        const segment = {
          id: segmentId,
          startTime: '',
          endTime: '',
        }

        videoSegments[videoId].push(segment)
        updateSegmentDisplay(videoId)
        updateButtonStates()
      }

      // 更新片段显示
      function updateSegmentDisplay(videoId) {
        const videoItem = document.querySelector(`[data-video-id="${videoId}"]`)
        const segmentsList = videoItem.querySelector('.segments-list')

        segmentsList.innerHTML = ''

        const segments = videoSegments[videoId] || []
        segments.forEach((segment, index) => {
          const segmentItem = document.createElement('div')
          segmentItem.className = 'segment-item'

          const segmentTime = document.createElement('div')
          segmentTime.className = 'segment-time'

          const startInput = document.createElement('input')
          startInput.type = 'text'
          startInput.className = 'time-input'
          startInput.placeholder = '00:00:00'
          startInput.value = segment.startTime
          startInput.addEventListener('input', (e) => {
            segment.startTime = e.target.value
            updateSegmentMarkers()
          })

          const endInput = document.createElement('input')
          endInput.type = 'text'
          endInput.className = 'time-input'
          endInput.placeholder = '00:00:00'
          endInput.value = segment.endTime
          endInput.addEventListener('input', (e) => {
            segment.endTime = e.target.value
            updateSegmentMarkers()
          })

          const removeBtn = document.createElement('button')
          removeBtn.className = 'remove-segment'
          removeBtn.textContent = '×'
          removeBtn.addEventListener('click', () => {
            // 保存当前播放状态
            const wasPlaying = !mainVideo.paused
            const currentTime = mainVideo.currentTime

            segments.splice(index, 1)
            updateSegmentDisplay(videoId)
            updateSegmentMarkers()
            updateButtonStates()

            // 恢复播放状态
            if (wasPlaying && mainVideo.paused) {
              mainVideo.currentTime = currentTime
              mainVideo.play().catch(() => {})
            }
          })

          segmentTime.appendChild(startInput)
          segmentTime.appendChild(document.createTextNode(' - '))
          segmentTime.appendChild(endInput)

          segmentItem.appendChild(segmentTime)
          segmentItem.appendChild(removeBtn)

          segmentsList.appendChild(segmentItem)
        })
      }

      // 更新片段标记
      function updateSegmentMarkers() {
        if (!currentVideoId || !mainVideo.duration) return

        segmentMarkers.innerHTML = ''

        const segments = videoSegments[currentVideoId] || []
        segments.forEach((segment) => {
          if (segment.startTime) {
            const startSeconds = timeToSeconds(segment.startTime)
            if (startSeconds >= 0 && startSeconds <= mainVideo.duration) {
              const startMarker = document.createElement('div')
              startMarker.className = 'segment-marker start'
              startMarker.style.left = `${
                (startSeconds / mainVideo.duration) * 100
              }%`
              segmentMarkers.appendChild(startMarker)
            }
          }

          if (segment.endTime) {
            const endSeconds = timeToSeconds(segment.endTime)
            if (endSeconds >= 0 && endSeconds <= mainVideo.duration) {
              const endMarker = document.createElement('div')
              endMarker.className = 'segment-marker end'
              endMarker.style.left = `${
                (endSeconds / mainVideo.duration) * 100
              }%`
              segmentMarkers.appendChild(endMarker)
            }
          }
        })

        // 更新按钮状态，确保合并按钮状态正确
        updateButtonStates()
      }

      // 处理所有片段
      async function processAllSegments(shouldMerge = false) {
        if (!ffmpeg) {
          showMessage('❌ FFmpeg未初始化', 'error')
          return
        }

        const allSegments = []

        // 收集所有有效片段
        for (const videoId in videoSegments) {
          const videoFile = videoFiles.find((v) => v.id == videoId)
          const segments = videoSegments[videoId]

          segments.forEach((segment) => {
            if (segment.startTime && segment.endTime) {
              allSegments.push({
                videoFile,
                segment,
                videoId,
              })
            }
          })
        }

        if (allSegments.length === 0) {
          showMessage('❌ 没有有效的片段可处理', 'error')
          return
        }

        try {
          processedSegments = []

          for (let i = 0; i < allSegments.length; i++) {
            const { videoFile, segment, videoId } = allSegments[i]

            updateProgress(
              (i / allSegments.length) * 100,
              `处理片段 ${i + 1}/${allSegments.length}: ${videoFile.name}`
            )

            const outputFileName = await processSegment(videoFile, segment, i)
            if (outputFileName) {
              const data = ffmpeg.FS('readFile', outputFileName)
              const blob = new Blob([data.buffer], { type: 'video/mp4' })

              processedSegments.push({
                fileName: outputFileName,
                originalName: videoFile.name,
                segmentIndex: i,
                blob: blob,
              })
            }
          }

          if (shouldMerge && processedSegments.length > 0) {
            // 如果选择合并模式，直接调用合并函数
            await mergeAllSegments()
          } else {
            // 单独下载模式
            for (let i = 0; i < processedSegments.length; i++) {
              const segment = processedSegments[i]
              const url = URL.createObjectURL(segment.blob)
              const a = document.createElement('a')
              a.href = url
              a.download = segment.fileName
              a.click()

              // 释放URL对象
              setTimeout(() => URL.revokeObjectURL(url), 100)

              // 清理文件
              try {
                ffmpeg.FS('unlink', segment.fileName)
              } catch (e) {
                console.warn('清理文件失败:', segment.fileName)
              }
            }

            updateProgress(100, '✅ 所有片段处理完成')
            showMessage(
              `✅ 成功处理 ${processedSegments.length} 个片段`,
              'success'
            )
          }

          // 更新按钮状态
          updateButtonStates()
        } catch (error) {
          console.error('处理片段失败:', error)
          showMessage(`❌ 处理失败: ${error.message}`, 'error')
        }
      }

      // 处理单个片段
      async function processSegment(videoFile, segment, index) {
        const inputFileName = `input_${index}.${getFileExtension(
          videoFile.name
        )}`
        const outputFileName = `segment_${index}_${videoFile.name}`

        try {
          // 写入输入文件
          ffmpeg.FS('writeFile', inputFileName, await fetchFile(videoFile.file))

          // 构建FFmpeg命令
          const startSeconds = timeToSeconds(segment.startTime)
          const endSeconds = timeToSeconds(segment.endTime)
          const duration = endSeconds - startSeconds

          const command = [
            '-i',
            inputFileName,
            '-ss',
            startSeconds.toString(),
            '-t',
            duration.toString(),
            '-c:v',
            'libx264',
            '-c:a',
            'aac',
            '-preset',
            'fast',
            '-crf',
            '23',
            '-movflags',
            '+faststart',
            '-avoid_negative_ts',
            'make_zero',
            outputFileName,
          ]

          // 执行FFmpeg命令
          await ffmpeg.run(...command)

          // 清理输入文件
          ffmpeg.FS('unlink', inputFileName)

          return outputFileName
        } catch (error) {
          console.error(`处理片段失败 (${index}):`, error)
          throw error
        }
      }

      // 合并所有片段
      async function mergeAllSegments() {
        // 收集所有视频的所有有效片段
        const allValidSegments = []

        for (const videoId in videoSegments) {
          const videoFile = videoFiles.find((v) => v.id == videoId)
          const segments = videoSegments[videoId] || []

          segments.forEach((segment, index) => {
            if (segment.startTime && segment.endTime) {
              allValidSegments.push({
                videoFile,
                segment,
                videoId,
                originalIndex: index,
              })
            }
          })
        }

        if (allValidSegments.length === 0) {
          showMessage('❌ 没有有效的片段可合并', 'error')
          return
        }

        try {
          updateProgress(0, '准备合并所有片段...')

          let segmentsToMerge = []

          // 如果有已处理的片段，直接使用
          if (processedSegments.length > 0) {
            segmentsToMerge = processedSegments
          } else {
            // 否则处理所有视频的所有片段
            updateProgress(10, '正在处理所有片段...')

            for (let i = 0; i < allValidSegments.length; i++) {
              const { videoFile, segment } = allValidSegments[i]

              updateProgress(
                10 + (i * 40) / allValidSegments.length,
                `处理片段 ${i + 1}/${allValidSegments.length}...`
              )

              const outputFileName = await processSegment(videoFile, segment, i)
              segmentsToMerge.push({
                fileName: outputFileName,
                segment: segment,
              })
            }
          }

          if (segmentsToMerge.length === 0) {
            showMessage('❌ 没有可合并的片段', 'error')
            return
          }

          updateProgress(50, '正在合并所有片段...')

          // 创建合并列表文件
          const fileList = segmentsToMerge
            .map((segment) => `file '${segment.fileName}'`)
            .join('\n')

          ffmpeg.FS('writeFile', 'filelist.txt', fileList)

          const outputFileName = `merged_all_videos_${Date.now()}.mp4`

          // 执行合并命令
          await ffmpeg.run(
            '-f',
            'concat',
            '-safe',
            '0',
            '-i',
            'filelist.txt',
            '-c',
            'copy',
            outputFileName
          )

          updateProgress(90, '准备下载文件...')

          // 读取合并后的文件
          const data = ffmpeg.FS('readFile', outputFileName)
          const blob = new Blob([data.buffer], { type: 'video/mp4' })

          // 创建下载链接
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = outputFileName
          a.click()

          // 清理文件
          ffmpeg.FS('unlink', 'filelist.txt')
          ffmpeg.FS('unlink', outputFileName)

          // 清理临时处理的片段文件
          segmentsToMerge.forEach((segment) => {
            try {
              ffmpeg.FS('unlink', segment.fileName)
            } catch (e) {
              console.warn('清理文件失败:', segment.fileName)
            }
          })

          updateProgress(100, '✅ 合并完成')
          showMessage(
            `✅ 成功合并 ${allValidSegments.length} 个片段`,
            'success'
          )
        } catch (error) {
          console.error('合并失败:', error)
          showMessage(`❌ 合并失败: ${error.message}`, 'error')
        }
      }

      // 创建下载链接
      function createDownloadLinks() {
        // 这里可以添加下载链接的UI
        processedSegments.forEach((segment) => {
          try {
            const data = ffmpeg.FS('readFile', segment.fileName)
            const blob = new Blob([data.buffer], { type: 'video/mp4' })
            const url = URL.createObjectURL(blob)

            const a = document.createElement('a')
            a.href = url
            a.download = segment.fileName
            a.click()

            // 清理文件
            ffmpeg.FS('unlink', segment.fileName)
          } catch (error) {
            console.error(`下载文件失败: ${segment.fileName}`, error)
          }
        })
      }

      // 下载日志
      function downloadLogs() {
        if (processingLogs.length === 0) {
          showMessage('❌ 没有日志可下载', 'error')
          return
        }

        const logContent = processingLogs.join('\n')
        const blob = new Blob([logContent], { type: 'text/plain' })
        const url = URL.createObjectURL(blob)

        const a = document.createElement('a')
        a.href = url
        a.download = `ffmpeg_logs_${new Date()
          .toISOString()
          .slice(0, 19)
          .replace(/:/g, '-')}.txt`
        a.click()

        URL.revokeObjectURL(url)
        showMessage('✅ 日志下载完成', 'success')
      }

      // 重置所有
      function resetAll() {
        if (confirm('确定要重置所有内容吗？这将清除所有视频和片段。')) {
          videoFiles = []
          videoSegments = {}
          processedSegments = []
          processingLogs = []
          currentVideoId = null

          videoList.innerHTML = ''
          mainVideo.style.display = 'none'
          noVideoPlaceholder.style.display = 'block'

          updateProgress(0, '等待开始...')
          updateButtonStates()

          showMessage('✅ 已重置所有内容', 'success')
        }
      }

      // 更新按钮状态
      function updateButtonStates() {
        const hasVideos = videoFiles.length > 0
        const hasCurrentVideo = currentVideoId !== null

        // 检查所有视频是否有有效片段
        let hasValidSegments = false
        for (const videoId in videoSegments) {
          if (
            videoSegments[videoId]?.some((seg) => seg.startTime && seg.endTime)
          ) {
            hasValidSegments = true
            break
          }
        }

        const hasSegments =
          hasCurrentVideo && videoSegments[currentVideoId]?.length > 0
        const hasProcessedSegments = processedSegments.length > 0

        // 添加片段按钮：需要选中视频
        addSegmentBtn.disabled = !hasCurrentVideo

        // 处理片段按钮：需要有效的片段（独立功能，可单独使用）
        processSegmentsBtn.disabled = !hasValidSegments

        // 合并片段按钮：只要有有效片段就可以启用，支持直接合并
        mergeSegmentsBtn.disabled = !hasValidSegments
      }

      // 更新进度
      function updateProgress(percent, text) {
        progressFill.style.width = `${percent}%`
        progressText.textContent = text
      }

      // 显示消息
      function showMessage(message, type = '') {
        statusMessage.textContent = message
        statusMessage.className = `status-message ${type}`

        if (type) {
          setTimeout(() => {
            statusMessage.textContent = ''
            statusMessage.className = 'status-message'
          }, 3000)
        }
      }

      // 工具函数
      function formatTime(seconds) {
        if (!seconds || isNaN(seconds)) return '00:00:00'

        const hours = Math.floor(seconds / 3600)
        const minutes = Math.floor((seconds % 3600) / 60)
        const secs = Math.floor(seconds % 60)

        return `${hours.toString().padStart(2, '0')}:${minutes
          .toString()
          .padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
      }

      function timeToSeconds(timeStr) {
        if (!timeStr || typeof timeStr !== 'string') return 0

        const parts = timeStr.split(':')
        if (parts.length !== 3) return 0

        const hours = parseInt(parts[0]) || 0
        const minutes = parseInt(parts[1]) || 0
        const seconds = parseInt(parts[2]) || 0

        return hours * 3600 + minutes * 60 + seconds
      }

      function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes'

        const k = 1024
        const sizes = ['Bytes', 'KB', 'MB', 'GB']
        const i = Math.floor(Math.log(bytes) / Math.log(k))

        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
      }

      function getFileExtension(filename) {
        return filename.split('.').pop().toLowerCase()
      }

      // 进度条悬停功能
      let previewVideo = null
      let tooltipVisible = false

      // 进度条长按选择范围功能
      let isSelecting = false
      let selectionStartTime = 0
      let selectionEndTime = 0
      let selectionStartX = 0
      let rangeSelectionElement = null

      function showProgressTooltip() {
        if (!mainVideo.src || !mainVideo.duration || isNaN(mainVideo.duration))
          return

        const tooltip = document.getElementById('progressTooltip')
        if (!tooltip) return

        tooltip.classList.add('show')
        tooltipVisible = true

        // 创建预览视频元素
        if (!previewVideo) {
          previewVideo = document.createElement('video')
          previewVideo.src = mainVideo.src
          previewVideo.muted = true
          previewVideo.style.width = '100%'
          previewVideo.style.height = '100%'
          previewVideo.style.objectFit = 'cover'

          const preview = document.getElementById('progressPreview')
          if (!preview) return

          const placeholder = preview.querySelector(
            '.progress-preview-placeholder'
          )
          if (placeholder) {
            placeholder.style.display = 'none'
          }
          preview.appendChild(previewVideo)
        }
      }

      function updateProgressTooltip(event) {
        if (
          !tooltipVisible ||
          !mainVideo.src ||
          !mainVideo.duration ||
          isNaN(mainVideo.duration)
        )
          return

        const rect = progressContainer.getBoundingClientRect()
        const x = event.clientX - rect.left
        const percentage = Math.max(0, Math.min(1, x / rect.width))
        const time = percentage * mainVideo.duration

        // 更新提示位置
        const tooltip = document.getElementById('progressTooltip')
        if (!tooltip) return

        const tooltipRect = tooltip.getBoundingClientRect()
        const tooltipWidth = tooltipRect.width
        const progressWidth = rect.width

        // 计算提示框的左边距，确保宽度中心始终对应鼠标位置
        // 允许浮框在边界处部分超出进度条，确保中心对齐
        let leftPosition = x - tooltipWidth / 2

        // 更新时间显示
        const timeDisplay = document.getElementById('progressTime')
        if (timeDisplay) {
          timeDisplay.textContent = formatTime(time)
        }

        // 更新预览视频时间
        if (previewVideo && Math.abs(previewVideo.currentTime - time) > 0.5) {
          previewVideo.currentTime = time
        }

        // 直接设置像素位置，确保宽度中心始终对应鼠标
        tooltip.style.left = leftPosition + 'px'
      }

      function hideProgressTooltip() {
        const tooltip = document.getElementById('progressTooltip')
        if (!tooltip) return

        tooltip.classList.remove('show')
        tooltipVisible = false

        // 清理预览视频
        if (previewVideo) {
          const preview = document.getElementById('progressPreview')
          if (preview) {
            const placeholder = preview.querySelector(
              '.progress-preview-placeholder'
            )
            if (placeholder) {
              placeholder.style.display = 'flex'
            }
            if (previewVideo.parentNode) {
              previewVideo.parentNode.removeChild(previewVideo)
            }
          }
          previewVideo = null
        }
      }

      // 音量控制功能
      function toggleVolumeTooltip(event) {
        event.stopPropagation()
        const tooltip = volumeTooltip
        const isVisible = tooltip.classList.contains('show')
        
        if (isVisible) {
          hideVolumeTooltip()
        } else {
          showVolumeTooltip()
        }
      }

      function showVolumeTooltip() {
        volumeTooltip.classList.add('show')
        // 同步当前音量值
        const currentVolume = Math.round(mainVideo.volume * 100)
        volumeSlider.value = currentVolume
        volumePercentage.textContent = currentVolume + '%'
        updateVolumeIcon(currentVolume)
      }

      function hideVolumeTooltip() {
        volumeTooltip.classList.remove('show')
      }

      function updateVolume() {
        const volume = parseInt(volumeSlider.value)
        mainVideo.volume = volume / 100
        volumePercentage.textContent = volume + '%'
        updateVolumeIcon(volume)
      }

      function updateVolumeIcon(volume) {
        let icon = '🔊'
        if (volume === 0) {
          icon = '🔇'
        } else if (volume < 30) {
          icon = '🔈'
        } else if (volume < 70) {
          icon = '🔉'
        }
        volumeBtn.textContent = icon
      }

      // 进度条交互处理函数
      function handleProgressMouseDown(event) {
        if (!mainVideo.duration || event.button !== 0) return // 只响应左键

        event.preventDefault()
        event.stopPropagation()

        isLongPress = false
        isProgressInteracting = true // 标记开始进度条交互
        const rect = progressContainer.getBoundingClientRect()
        selectionStartX = event.clientX - rect.left
        const percentage = Math.max(
          0,
          Math.min(1, selectionStartX / rect.width)
        )
        selectionStartTime = percentage * mainVideo.duration

        // 设置长按定时器
        clickTimer = setTimeout(() => {
          isLongPress = true
          startRangeSelection()
        }, longPressThreshold)
      }

      function handleProgressMouseMove(event) {
        if (isSelecting && isLongPress) {
          updateRangeSelection(event)
        }
      }

      function handleProgressMouseUp(event) {
        // 只在真正的进度条交互时才处理
        if (!isProgressInteracting) return
        
        // 清除定时器
        if (clickTimer) {
          clearTimeout(clickTimer)
          clickTimer = null
        }

        if (isLongPress && isSelecting) {
          // 长按选择结束
          endRangeSelection(event)
        } else if (!isLongPress) {
          // 单击跳转
          seekVideo(event)
          // 单击后开始播放视频
          if (mainVideo.paused) {
            mainVideo.play()
          }
        }

        isLongPress = false
        isProgressInteracting = false // 重置交互标志
      }

      // 开始范围选择
      function startRangeSelection() {
        isSelecting = true

        // 获取或创建范围选择元素
        rangeSelectionElement = document.getElementById('rangeSelection')
        if (rangeSelectionElement) {
          rangeSelectionElement.style.display = 'block'
          rangeSelectionElement.style.left = selectionStartX + 'px'
          rangeSelectionElement.style.width = '0px'
        }
      }

      // 更新范围选择
      function updateRangeSelection(event) {
        if (!isSelecting || !mainVideo.duration) return

        const rect = progressContainer.getBoundingClientRect()
        const currentX = event.clientX - rect.left
        const percentage = Math.max(0, Math.min(1, currentX / rect.width))
        const currentTime = percentage * mainVideo.duration

        // 计算选择范围
        const startX = Math.min(selectionStartX, currentX)
        const endX = Math.max(selectionStartX, currentX)
        const width = endX - startX

        // 更新选择范围显示
        if (rangeSelectionElement) {
          rangeSelectionElement.style.left = startX + 'px'
          rangeSelectionElement.style.width = width + 'px'
        }

        // 更新结束时间
        selectionEndTime = currentTime
      }

      // 结束范围选择
      function endRangeSelection(event) {
        if (!isSelecting) return

        isSelecting = false

        // 如果选择了有效范围，自动标记起始和结束时间
        if (Math.abs(selectionEndTime - selectionStartTime) > 0.1) {
          // 至少0.1秒的差异
          const startTime = Math.min(selectionStartTime, selectionEndTime)
          const endTime = Math.max(selectionStartTime, selectionEndTime)

          if (currentVideoId) {
            // 创建新片段或使用最后一个未完成的片段
            let segments = videoSegments[currentVideoId]
            let targetSegment = segments[segments.length - 1]

            if (!targetSegment || targetSegment.endTime) {
              addSegment(currentVideoId)
              segments = videoSegments[currentVideoId]
              targetSegment = segments[segments.length - 1]
            }

            // 设置起始和结束时间
            targetSegment.startTime = formatTime(startTime)
            targetSegment.endTime = formatTime(endTime)

            updateSegmentDisplay(currentVideoId)
            updateSegmentMarkers()
            updateButtonStates()

            showMessage(
              `✅ 已选择时间范围: ${formatTime(startTime)} - ${formatTime(
                endTime
              )}`,
              'success'
            )
          }
        }

        // 隐藏选择范围
        if (rangeSelectionElement) {
          rangeSelectionElement.style.display = 'none'
        }
      }

      // 页面加载完成后初始化
      window.addEventListener('load', init)
    </script>
  </body>
</html>
